package com.example.mine_platform.service.impl;

import com.example.mine_platform.commom.Result;
import com.example.mine_platform.mapper.MaterialMapper;
import com.example.mine_platform.pojo.dto.MaterialDTO;
import com.example.mine_platform.pojo.dto.MaterialNewDTO;
import com.example.mine_platform.pojo.entities.Material;
import com.example.mine_platform.pojo.vo.MaterialVO;
import com.example.mine_platform.service.MaterialService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class MaterialServiceImpl implements MaterialService {
    @Resource
    private MaterialMapper materialMapper;

    @Override
    public List<MaterialVO> getAllMaterials() {
        List<Material> materialList = materialMapper.getAllMaterials();
        List<MaterialVO> materialVOList = new ArrayList<>();
        for (Material x : materialList) {
            MaterialVO materialVO = new MaterialVO();
            materialVO.setId(x.getId());
            materialVO.setName(x.getName());
            materialVO.setType(x.getType());
            materialVO.setStock_quantity(x.getStockQuantity());
            materialVO.setPrice(x.getPrice());
            materialVOList.add(materialVO);
        }
        return materialVOList;
    }

    @Override
    public Material getMaterialById(Integer id) {
        Material material = materialMapper.selectByPrimaryKey(id);
        return material;
    }

    @Override
    public Result insertMaterial(MaterialNewDTO materialNewDTO) {
        Material material = new Material();
        material.setName(materialNewDTO.getName());
        material.setDescribe(materialNewDTO.getDescribe());
        material.setType(materialNewDTO.getType());
        material.setStockQuantity(materialNewDTO.getStock_quantity());
        material.setPrice(materialNewDTO.getPrice());
        materialMapper.insertSelective(material);
        return Result.success();
    }

    @Override
    public Result updateMaterial(MaterialDTO materialDTO) {
        Integer id = materialDTO.getId();
        Material material = materialMapper.selectByPrimaryKey(id);
        material.setName(materialDTO.getName());
        material.setDescribe(materialDTO.getDescribe());
        material.setType(materialDTO.getType());
        material.setStockQuantity(materialDTO.getStock_quantity());
        material.setPrice(materialDTO.getPrice());
        material.setUpdateTime(new Timestamp(System.currentTimeMillis()).toLocalDateTime());
        materialMapper.updateByPrimaryKey(material);
        return Result.success();
    }

    @Override
    public Result deleteMaterial(Integer id) {
        Material material = materialMapper.selectByPrimaryKey(id);
        material.setDeleted((byte) 1);
        materialMapper.updateByPrimaryKey(material);
        return Result.success();
    }
}
